package gui;

import input.InputManager;

import java.util.List;

import main.Config;
import main.Core;
import model.GameObject;
import model.ImageSprite;
import action.ActionResponse;
import action.Blend2DAction;
import action.PeriodicAction;
import data.Vector2;

/**
 * 
 * @author YvensDesktop
 *
 */
public class Arrow extends ImageSprite{
	
	private PeriodicAction periodicAction;
	private Blend2DAction blendAction; 
	private List<Vector2> positions;
	private float blendSpeed;
	private int actualPosition;
	
	
	public Arrow(List<Vector2> positions, GameObject owner, Core core) {
		super((String)Config.getConfig("arrowPath"), positions.get(0), (Vector2)Config.getConfig("arrowSize"), owner, core);	
		
		this.positions = positions;
		actualPosition = 0;
		
		periodicAction = createPeriodicAction();
		blendAction = null;
		
		blendSpeed = 0.2f;
		
		this.getActions().add(periodicAction);
	}

	
	
	private void move(int variation) {
		if (null == blendAction || !blendAction.isRunning()) {
			int nextPosition = actualPosition + variation;
			
			if(nextPosition >= positions.size()){
				nextPosition = 0;
			}
			else if(nextPosition < 0){
				nextPosition = positions.size() - 1;
			}
			
			blendAction = createBlendAction(nextPosition);
			this.getActions().add(blendAction);
		}
	}

	@Override
	public void update(float elapsedTime){
		if(InputManager.keyboard.getDown().wasPressed()){
			move(+1);
		}	
		if(InputManager.keyboard.getUp().wasPressed()){
			move(-1);
		}
		super.update(elapsedTime);
	}
	
	private PeriodicAction createPeriodicAction(){		
		final PeriodicAction output = new PeriodicAction(
				10f, true, 2f, null);
		output.setResponse( new ActionResponse("arrow", this) {
			@Override
			public void update(float elapsedTime) { 
				((Arrow)getHash().get("arrow")).setOffset(new Vector2(output.getActualValue(), 0f)); 
			}
			
			@Override
			public void finished() {}
		});
		
		return output;
	}
	private Blend2DAction createBlendAction(int nextPosition){
		final Blend2DAction output = new Blend2DAction(
				getPositions().get(actualPosition), getPositions().get(nextPosition), false, blendSpeed, null);

		output.setResponse(new ActionResponse("arrow", this) {
			@Override
			public void update(float elapsedTime) { 
				((Arrow)getHash().get("arrow")).setPosition(output.getActualValue()); 
			}
			
			@Override
			public void finished() {}
		});	
		
		actualPosition = nextPosition;
		return output;
	}
	
	public float getBlendSpeed() {
		return blendSpeed;
	}
	public void setBlendSpeed(float blendSpeed) {
		this.blendSpeed = blendSpeed;
	}
	public int getActualPosition() {
		return actualPosition;
	}
	public List<Vector2> getPositions() {
		return positions;
	}
}
